<?php
 import('Com.Images.ImgSplice');
class RssAction extends Action {
	
	var $PickRoot = "";
	
	var $dbcon =array(
		'DB_TYPE'=>'mysql',
		'DB_NAME'=>'uh5',
		'DB_HOST'=>'localhost',
		'DB_USER'=>'root',
		'DB_PWD'=>'',
		'DB_PREFIX'=>'',
		'URL_MODEL'=>0
);
/***
 *			// logCmd($description);
			preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp]))[\'|\"].*?[\/]?>/",$description,$ereg);
			// if(!empty($ereg)){
			// 	mkdir($this->PickRoot."/".$doms."/".$V);
			// 	foreach ($ereg[1] as $j=>$img) {
			// 		if(substr($img,0,4) != "http"){$img=$RssDom."/".$img;}
			// 		logCmd($img);					
			// 		wfile($this->PickRoot."/".$doms."/".$V."/".$j.".jpg",get_Url_File($img));
			// 	}								
			// 	$imgsplice = new ImgSplice($this->PickRoot."/".$doms."/".$V);
   			//      		$imgsplice->temps();
			// }
			// preg_match_all("/<[a|A].*?href=[\'|\"](.*)[\'|\"].*?[\/]?>/",$description,$ereg);
			// print_r($ereg);
 */





	function __construct() {
		$this->PickRoot = PICK_DIR . MODULE_NAME . DIRECTORY_SEPARATOR;
		if (! is_dir ( $this->PickRoot )) {
			mkdir ( $this->PickRoot );
		}
		load ( "@.dom" );
		//logCmd("Start");
	

	}
	
	function __destruct() {
		//logCmd("End");
	}

	 public function get_redirect_url($url){
    	$redirect_url = null;
    
    	$url_parts = @parse_url($url);
    	if (!$url_parts) return false;
    	if (!isset($url_parts['host'])) return false; //can't process relative URLs
    	if (!isset($url_parts['path'])) $url_parts['path'] = '/';
    
    	$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
    	if (!$sock) return false;
    
    	$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
    	$request .= 'Host: ' . $url_parts['host'] . "\r\n";
    	$request .= "Connection: Close\r\n\r\n";
    	fwrite($sock, $request);
    	$response = '';
    	while(!feof($sock)) $response .= fread($sock, 8192);
    	fclose($sock);
    
    	if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
    		if ( substr($matches[1], 0, 1) == "/" )
    			return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
    		else
    			return trim($matches[1]);
    	} else {
    		return false;
    	}
    
    }


    public function Gurl($url){
    	$domain = get_domain($url);
    	$geturl= $url;
    	while (true) {
    		$geturl = $this->get_redirect_url($geturl);
    		if(!$geturl ||get_domain($geturl)!=$domain){break;}
    	}

    	if($geturl==""){
    		$geturl= $url;
    	}

    	$domain = get_domain($geturl);
		$query = (parse_url($geturl));
		parse_str($query['query'],$query);
    	if($domain =="yiqifa.com"){
    		$geturl=$query['t'];
    	}else if($domain=="taobao.com"|| $domain=="tmall.com"){



    	}

    	return $geturl;
  
    }

	

	public function index() {
		//无限循环执行
		// while (true) {
		// 	CmdExec("Rss Public2DB");			
		// 	$time = 600;
		// 	if(date("H")>9){
		// 		$time = 60 ;
		// 	}
		// 	logCmd("Please wait ".date("Y-m-d H:i:s",time()+$time)." Second,The Next Run !");
		// 	logCmd("",false);
		// 	while (($time--)>0) {
		// 		echo ($time+1).".";
		// 		sleep(1);
		// 	}
		// }

		// $Hosts = M('Hosts'); 

// 
		logCmd($this->Gurl("http://url.douqin.com/12496078374"));





		// $url ="http://www.tdpyh.com/feed";
		// $Node =$this->WpFeed($url);	
		// $RssUrl = (pathinfo($url));
		// $RssDom = $RssUrl['dirname'];
		// $doms=get_domain($RssDom);
		// mkdir($this->PickRoot."/".$doms);
		// foreach ($Node['item'] as $V=>$item) {
		// 	$description=empty($item['content'])?$item['description']:$item['content'];
		// 	$html= str_get_html($description);
		// 	// foreach ($html->find("img") as $img) {
		// 	// 	logCmd($img->src);
		// 	// }

		// 	foreach ($html->find("a") as $a) {
		// 		logCmd("----------------------------------------");
		// 		logCmd($a->href);
		// 		logCmd($this->Gurl($a->href));
		// 	}

		// }



		// file_put_contents($this->PickRoot."/li555.txt", print_r($Node,true));
	}
	
	public function Public2DB() {
		$Hosts= M("Hosts");
		$lastTimesMap=0;
		$Host = $Hosts->order("updated asc")->find();
		// $Host = $Hosts->where("host_id =  16")->find();

		if(!empty($Host['indexurl'])){

		logCmd("URL:".$Host['indexurl']);

		$HostInfo =M("Hostinfo");
        $TagesInfo = M("TagesInfo");
        $HostInfoHasTages = M("HostinfoHasTages");
		$node = $this->WpFeed($Host['indexurl']);
		file_put_contents($this->PickRoot."/".$Host['host_id'].".txt", print_r($node,true));
		$lastTimesMap=intval($node['lastTimesMap']);
		if($lastTimesMap == 0||$lastTimesMap > $Host['created']){
			logCmd("Item Size :".Count($node['item']));
			$OldMunber=0;
			foreach ($node['item'] as $item) {
				if($OldMunber>3)break;	
				$Info=array();
				$Info['host_id'] = $Host['host_id'];
				$Info['link'] =$item['link'];
				$InfoId=$HostInfo->where($Info)->getField("hinfo_id");
					if(intval($InfoId)==0){

						$Info['title'] = $item['title'];
						$Info['content'] = empty($item['content'])?$item['description']:$item['content'];
						$Info['created'] =intval($item["timestamp"]);
						$Info['updated'] =time();
						$Info['comments'] = $item['comments'];	
						$InfoId = $HostInfo->data($Info)->add();
								
						foreach ($item['category'] as $cat) {
							$catdata = array('cnname' =>$cat,"tage_class_id"=>"10001" );
							$tagid =$TagesInfo->where($catdata)->getField("tage_id");
							if(intval($tagid)==0){
								$tagid = $TagesInfo->data($catdata)->add();
							}
							$HostInfoHasTages->data(array("tage_id"=>$tagid,"hinfo_id"=>$InfoId))->add();
						}
						logCmd("Item News: ".$item['link']);
					}else{
						$OldMunber++;
						logCmd("Host Old: ".$item['link']);
					}
				}
			}else{
				logCmd("Host ID: ".$Host['host_id']." Not updated!");
			}
		}else{
			logCmd("Host ID: ".$Host['host_id']." IndexUrl is NULL!");
		}
		$Hosts->where(array("host_id"=>$Host['host_id']))->data(array("updated"=>time(),"created"=>$lastTimesMap))->save();
		logCmd($Hosts->_sql());
	}
	
	private function WpFeed($rss) {
		$ns = array (
			'content' => 'http://purl.org/rss/1.0/modules/content/', 'wfw' => 'http://wellformedweb.org/CommentAPI/', 'dc' => 'http://purl.org/dc/elements/1.1/' );
		
		$articles = array ();
		
		// step 1: 获得feed
		
		$html = file_get_contents($rss);
		$xml  =simplexml_load_string($html,'SimpleXMLElement', LIBXML_NOCDATA);
		// $xml = simplexml_load_file ( $rss, 'SimpleXMLElement', LIBXML_NOCDATA); 
		// print_r($xml);
		// step 2: 获得channel metadata
		

		$channel = array ();
		$channel ['title'] = ( string ) $xml->channel->title;
		$channel ['link'] = ( string ) $xml->channel->link;
		$channel ['description'] = ( string ) $xml->channel->description;
		$channel ['lastBuildDate'] = ( string ) $xml->channel->lastBuildDate;
		$channel ['lastTimesMap'] = strtotime(( string ) $xml->channel->lastBuildDate);
		$channel ['generator'] = ( string ) $xml->generator;
		$channel ['language'] = ( string ) $xml->channel->language;
		$channel ['item'] = array ();
		
		// step 3: 获得articles
		foreach ( $xml->channel->item as $item ) {

			$article = array ();
			$article ['channel'] = $rss;
			$article ['title'] = (( string ) $item->title);
			$article ['link'] = ( string ) $item->link;
			$article ['comments'] = ( string ) $item->comments;
			$article ['pubDate'] = ( string ) $item->pubDate;
			$article ['timestamp'] = strtotime ( $item->pubDate );
			$article ['description'] = (( string ) trim ( $item->description ));
			$article ['isPermaLink'] = ( string ) $item->guid ['isPermaLink'];
			$article ['category']=array();
			if(is_array($item->category)){
				foreach ($item->category  as  $categoryn) {
						$article ['category'][]=(string)($categoryn);
				}
			}


			// get data held in namespaces
			$content = $item->children ( $ns ['content'] );
			$dc = $item->children ( $ns ['dc'] );
			$wfw = $item->children ( $ns ['wfw'] );
			$article ['creator'] = ( string ) $dc->creator;			
			$article ['content'] = (( string ) trim ( $content->encoded ));
			$article ['commentRss'] = ( string ) $wfw->commentRss;
			// add this article to the list
			$channel ['item'] [] = $article;
		}
		return $channel;
	}

}